package com.dubbo.service.impl;

import com.dubbo.common.ResponseUtil;
import com.dubbo.domain.User;
import com.dubbo.domain.auth.Permission;
import com.dubbo.domain.info.ResultMessage;
import com.dubbo.mapper.auth.PermissionMapper;
import com.dubbo.mapper.auth.RoleMapper;
import com.dubbo.service.auth.PermissionService;
import com.dubbo.service.impl.base.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 用户权限
 * @author lihongwu
 * 2018年12月20日 上午11:43:50
 */
@Service
@Transactional(readOnly=false,rollbackFor=Exception.class)
public class PermissionServiceImpl extends BaseServiceImpl<Permission> implements PermissionService {

	@Autowired
	private PermissionMapper userPermissionMapper;
	@Autowired
	private RoleMapper roleMapper;
	
	/**
	 * 添加权限
	 *
	 * @author lihongwu
	 * 2018年12月20日 上午11:45:13
	 * @param json
	 * @return
	 */
	@Override
	public Map<String, Object> add(String name,String permission) {
		Permission userPermission = new Permission();
		userPermission.setName(name);
		
		if(userPermissionMapper.select(userPermission)!=null&&userPermissionMapper.select(userPermission).size()!=0) {
			return ResponseUtil.ajaxCheckError("权限已经存在!");
		}
		userPermission = new Permission();
		userPermission.setPermission(permission);
		
		if(userPermissionMapper.select(userPermission)!=null&&userPermissionMapper.select(userPermission).size()!=0) {
			return ResponseUtil.ajaxCheckError("权限已经存在!");
		}
		
		userPermission.setId(UUID.randomUUID().toString().replace("-", ""));
		userPermission.setName(name);
		userPermissionMapper.insertSelective(userPermission);
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK);
	}
	
	/**
	 * 获取登录用户的角色与权限
	 * @author chenluqiang
	 * @date 2018年12月20日 下午5:30:50 
	 * @param user
	 * @return
	 * @throws Exception 
	 */
	@Override
	public Map<String, Object> getRolesAndPermissions(User user) {
		//返回容器
		Map<String,Object> map = new HashMap<String,Object>();
		//获取角色list
		List<String> roles = roleMapper.getRolesByUserId(user.getId());
		//获取权限list
		List<String> permissions = userPermissionMapper.getPermissionsByUserId(user.getId());
		
		map.put("user",user);
		map.put("roles", roles);
		map.put("permissions", permissions);
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK,map);
	}

}
